import logging
import collections
from collections import Iterable
import os
import unicodedata

logger = logging.getLogger(__name__)


def load_vocab(vocab_file):
    """ 读取词典文件

    vocab_file：词典文件，为txt文件，编码默认为utf-8
        文件内，每一行一个词
    """
    vocab = collections.OrderedDict()
    with open(vocab_file, "r", encoding="utf-8") as reader:
        tokens = reader.readlines()
    for index, token in enumerate(tokens):
        token = token.rstrip("\n")
        vocab[token] = index
    return vocab


def whitespace_tokenize(text):
    text = text.strip()
    if not text:
        return []
    tokens = text.split()
    return tokens


class Tokenizer(object):
    """
    """
    def __init__(self,
                 vocab_file,
                 bos_token='[BOS]',
                 eos_token='[EOS]',
                 unk_token='[UNK]',
                 sep_token='[SEP]',
                 pad_token='[PAD]',
                 cls_token='[CLS]',
                 mask_token='[MASK]',
                 max_len=512,
                 do_lower_case=True,
                 do_basic_tokenize=True,
                 other_special_tokens=None,
                 never_split=None,
                 tokenize_chinese_chars=True,
                 strip_accents=True,
                 ):

        self.bos_token = bos_token
        self.eos_token = eos_token
        self.unk_token = unk_token
        self.sep_token = sep_token
        self.pad_token = pad_token
        self.cls_token = cls_token
        self.mask_token = mask_token

        if isinstance(vocab_file, dict):
            self.vocab = vocab_file
        elif isinstance(vocab_file, list):
            self.vocab = {token: i for i, token in enumerate(vocab_file)}
        elif os.path.isfile(vocab_file):
            self.vocab = load_vocab(vocab_file)
        else:
            raise ValueError(f" 请检查 vocab file 类型 当前只支持 dict、list、以及指定路径 三种情况")

        if self.unk_token not in self.vocab:
            raise ValueError(f"未登录词token {self.unk_token} 未在词典，请检查")

        self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])

        self.unk_token_id = self.vocab[self.unk_token]
        self.bos_token_id = self.vocab.get(self.bos_token, None)
        self.eos_token_id = self.vocab.get(self.eos_token, None)
        self.sep_token_id = self.vocab.get(self.sep_token, None)
        self.pad_token_id = self.vocab.get(self.pad_token, None)
        self.cls_token_id = self.vocab.get(self.cls_token, None)
        self.mask_token_id = self.vocab.get(self.mask_token, None)

        self.max_len = max_len if max_len is not None else int(1e12)
        self.vocab_size = len(self.vocab)

        self.do_lower_case = do_lower_case
        self.do_basic_tokenize = do_basic_tokenize

        self.all_special_tokens = [bos_token, unk_token, sep_token, pad_token, cls_token, mask_token]

        if isinstance(other_special_tokens, str):
            other_special_tokens = [other_special_tokens]
        self.all_special_tokens += list(other_special_tokens) if isinstance(other_special_tokens, (list, tuple)) else []

        self.all_special_ids = [self.vocab[token] for token in self.all_special_tokens if token in self.vocab]

        if do_basic_tokenize:
            if isinstance(never_split, str):
                never_split = [never_split]
            if isinstance(never_split, list) and len(never_split) > 0:
                to_never_split = never_split + self.all_special_ids
            else:
                to_never_split = None
            self.basic_tokenizer = BasicTokenizer(
                do_lower_case=do_lower_case,
                never_split=to_never_split,
                tokenize_chinese_chars=tokenize_chinese_chars,
                strip_accents=strip_accents,
            )
        self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token)

    def tokenize(self, text):
        """  这个子类实现 """
        return self._tokenize(text)

    def _tokenize(self, text):
        split_tokens = []
        if self.do_basic_tokenize:
            for token in self.basic_tokenizer.tokenize(text):
                if token in self.basic_tokenizer.never_split:
                    split_tokens.append(token)
                else:
                    split_tokens += self.wordpiece_tokenizer.tokenize(token)
        else:
            split_tokens = self.wordpiece_tokenizer.tokenize(text)
        return split_tokens

    def convert_tokens_to_ids(self, tokens):
        if tokens is None:
            return None

        if isinstance(tokens, str):
            return self._convert_token_to_id(tokens)

        ids = []
        for token in tokens:
            ids.append(self._convert_token_to_id(token))
        if len(ids) > self.max_len:
            logger.warning(f"Token 过长 警告 支持最长token:{self.max_len}  当前长度:{len(ids)}")
        return ids

    def _convert_token_to_id(self, token):
        return self.vocab.get(token, self.vocab.get(self.unk_token))

    def encode(self, **kwargs):
        """
        """
        raise NotImplementedError(f"子类实现 encode 方法")

    def convert_ids_to_tokens(self, ids, skip_special_tokens=False, stop_token_id=None):
        """ """
        if isinstance(ids, int):
            return self._convert_id_to_token(ids)
        tokens = []
        for index in ids:
            if index == stop_token_id:
                break
            if skip_special_tokens and index in self.all_special_ids:
                continue
            tokens.append(self._convert_id_to_token(index))
        return tokens

    def _convert_id_to_token(self, index):
        return self.ids_to_tokens.get(index, self.unk_token)

    def convert_tokens_to_string(self, tokens):
        return ' '.join(self.convert_ids_to_tokens(tokens))

    def decode(self, token_ids, skip_special_tokens=False, stop_token_id=None):
        """  解码
                skip_special_tokens: 跳过所有特殊token， Ture,跳过所有的特殊 token
                stop_token_id: 停止token id
                    当出现停止id的时候，将不在进行向后解码
                """
        if isinstance(token_ids, int):
            return self._decode([token_ids], skip_special_tokens=skip_special_tokens, stop_token_id=stop_token_id)
        elif not token_ids:
            return ""
        elif isinstance(token_ids, Iterable) and isinstance(token_ids[0], Iterable):
            return list(self.decode(sub_ids, skip_special_tokens=skip_special_tokens, stop_token_id=stop_token_id)
                        for sub_ids in token_ids)
        elif isinstance(token_ids, Iterable) and isinstance(token_ids[0], int):
            return self._decode(token_ids, skip_special_tokens=skip_special_tokens, stop_token_id=stop_token_id)
        else:
            return self._decode(token_ids, skip_special_tokens=skip_special_tokens, stop_token_id=stop_token_id)

    def _decode(self, token_ids, skip_special_tokens=False, stop_token_id=None):
        filtered_tokens = self.convert_ids_to_tokens(token_ids,
                                                     skip_special_tokens=skip_special_tokens,
                                                     stop_token_id=stop_token_id)
        text = ''.join(filtered_tokens)
        return text


class BasicTokenizer(object):
    def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True, strip_accents=None):
        if never_split is None:
            never_split = []
        self.do_lower_case = do_lower_case
        self.never_split = set(never_split)
        self.tokenize_chinese_chars = tokenize_chinese_chars
        self.strip_accents = strip_accents

    def tokenize(self, text, never_split=None):
        never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
        text = self._clean_text(text)
        if self.tokenize_chinese_chars:
            text = self._tokenize_chinese_chars(text)
        orig_tokens = whitespace_tokenize(text)
        split_tokens = []
        for token in orig_tokens:
            if token not in never_split:
                if self.do_lower_case:
                    token = token.lower()
                    if self.strip_accents is not False:
                        token = self._run_strip_accents(token)
                elif self.strip_accents:
                    token = self._run_strip_accents(token)
            split_tokens.extend(self._run_split_on_punc(token, never_split))
        output_tokens = whitespace_tokenize(" ".join(split_tokens))
        return output_tokens

    def _run_strip_accents(self, text):
        text = unicodedata.normalize("NFD", text)
        output = []
        for char in text:
            cat = unicodedata.category(char)
            if cat == "Mn":
                continue
            output.append(char)
        return "".join(output)

    def _run_split_on_punc(self, text, never_split=None):
        if never_split is not None and text in never_split:
            return [text]
        chars = list(text)
        i = 0
        start_new_word = True
        output = []
        while i < len(chars):
            char = chars[i]
            if _is_punctuation(char):
                output.append([char])
                start_new_word = True
            else:
                if start_new_word:
                    output.append([])
                start_new_word = False
                output[-1].append(char)
            i += 1
        return ["".join(x) for x in output]

    def _tokenize_chinese_chars(self, text):
        output = []
        for char in text:
            cp = ord(char)
            if self._is_chinese_char(cp):
                output.append(" ")
                output.append(char)
                output.append(" ")
            else:
                output.append(char)
        return "".join(output)

    def _is_chinese_char(self, cp):
        if (
            (cp >= 0x4E00 and cp <= 0x9FFF)
            or (cp >= 0x3400 and cp <= 0x4DBF)  #
            or (cp >= 0x20000 and cp <= 0x2A6DF)  #
            or (cp >= 0x2A700 and cp <= 0x2B73F)  #
            or (cp >= 0x2B740 and cp <= 0x2B81F)  #
            or (cp >= 0x2B820 and cp <= 0x2CEAF)  #
            or (cp >= 0xF900 and cp <= 0xFAFF)
            or (cp >= 0x2F800 and cp <= 0x2FA1F)  #
        ):  #
            return True
        return False

    def _clean_text(self, text):
        output = []
        for char in text:
            cp = ord(char)
            if cp == 0 or cp == 0xFFFD or _is_control(char):
                continue
            if _is_whitespace(char):
                output.append(" ")
            else:
                output.append(char)
        return "".join(output)


class WordpieceTokenizer(object):
    def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
        self.vocab = vocab
        self.unk_token = unk_token
        self.max_input_chars_per_word = max_input_chars_per_word

    def tokenize(self, text):
        output_tokens = []
        for token in whitespace_tokenize(text):
            chars = list(token)
            if len(chars) > self.max_input_chars_per_word:
                output_tokens.append(self.unk_token)
                continue

            is_bad = False
            start = 0
            sub_tokens = []
            while start < len(chars):
                end = len(chars)
                cur_substr = None
                while start < end:
                    substr = "".join(chars[start:end])
                    if start > 0:
                        substr = "##" + substr
                    if substr in self.vocab:
                        cur_substr = substr
                        break
                    end -= 1
                if cur_substr is None:
                    is_bad = True
                    break
                sub_tokens.append(cur_substr)
                start = end

            if is_bad:
                output_tokens.append(self.unk_token)
            else:
                output_tokens.extend(sub_tokens)
        return output_tokens


def _is_control(char):
    if char == "\t" or char == "\n" or char == "\r":
        return False
    cat = unicodedata.category(char)
    if cat.startswith("C"):
        return True
    return False


def _is_whitespace(char):
    if char == " " or char == "\t" or char == "\n" or char == "\r":
        return True
    cat = unicodedata.category(char)
    if cat == "Zs":
        return True
    return False


def _is_punctuation(char):
    cp = ord(char)
    if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126):
        return True
    cat = unicodedata.category(char)
    if cat.startswith("P"):
        return True
    return False
